# -*- coding: utf-8 -*-
"""
订单状态管理服务

处理订单状态流转、状态查询和状态更新
"""
from datetime import datetime
from typing import Dict, Any, List, Optional
from app.repositories.base_repository import BaseRepository
from app.models.order_status import (
    OrderStatus, PaymentType, OrderStatusTransition, 
    OrderStatusDisplay, PaymentStatus
)


class OrderStatusService:
    """订单状态管理服务"""
    
    def __init__(self):
        self.order_repo = BaseRepository("orders")
        self.status_log_repo = BaseRepository("order_status_logs")
    
    def update_order_status(self, order_id: str, new_status: str, user_id: str = None, 
                           notes: str = None, operator_type: str = "system") -> Dict[str, Any]:
        """更新订单状态"""
        try:
            # 获取当前订单信息
            order = self.order_repo.find_by_id("order_id", order_id)
            if not order:
                return {"success": False, "message": "订单不存在"}
            
            current_status = OrderStatus(order['order_status'])
            new_status_enum = OrderStatus(new_status)
            
            # 检查状态转换是否合法
            if not OrderStatusTransition.can_transition(current_status, new_status_enum):
                return {
                    "success": False, 
                    "message": f"不能从状态 '{current_status.value}' 转换到 '{new_status}'"
                }
            
            # 更新订单状态
            update_sql = """
                UPDATE orders SET 
                    order_status = %s,
                    updated_time = NOW()
                WHERE order_id = %s
            """
            result = self.order_repo.execute_custom_query(update_sql, [new_status, order_id], False)
            
            if result is not None:
                # 记录状态变更日志
                self._log_status_change(
                    order_id, current_status.value, new_status, 
                    operator_type, user_id, notes
                )
                
                return {
                    "success": True,
                    "message": "状态更新成功",
                    "data": {
                        "order_id": order_id,
                        "old_status": current_status.value,
                        "new_status": new_status,
                        "status_info": OrderStatusDisplay.get_status_info(new_status_enum)
                    }
                }
            else:
                return {"success": False, "message": "状态更新失败"}
                
        except ValueError as e:
            return {"success": False, "message": f"无效的状态值：{str(e)}"}
        except Exception as e:
            return {"success": False, "message": f"更新状态失败：{str(e)}"}
    
    def get_order_status_info(self, order_id: str, user_id: str = None) -> Dict[str, Any]:
        """获取订单状态信息"""
        try:
            # 获取订单信息
            order = self.order_repo.find_by_id("order_id", order_id)
            if not order:
                return {"success": False, "message": "订单不存在"}
            
            # 权限检查（如果提供了user_id）
            if user_id and order['customer_id'] != user_id:
                return {"success": False, "message": "无权限查看该订单"}
            
            # 获取状态信息 - 兼容现有状态值
            order_status_value = order['order_status']
            try:
                current_status = OrderStatus(order_status_value)
            except ValueError:
                # 兼容现有的状态值
                status_mapping = {
                    'pending': OrderStatus.PENDING,
                    'processing': OrderStatus.PAID,  # 将processing映射为已支付
                    'completed': OrderStatus.COMPLETED,
                    'cancelled': OrderStatus.CANCELLED
                }
                current_status = status_mapping.get(order_status_value, OrderStatus.PENDING)
            
            status_info = OrderStatusDisplay.get_status_info(current_status)
            
            # 获取支付类型
            payment_method = order.get('payment_method', '')
            payment_type = self._get_payment_type_from_method(payment_method)
            
            # 获取可能的下一个状态
            possible_next_statuses = self._get_possible_next_statuses(current_status, payment_type)
            
            # 获取状态历史
            status_history = self._get_status_history(order_id)
            
            return {
                "success": True,
                "data": {
                    "order_id": order_id,
                    "current_status": {
                        "status": current_status.value,
                        "info": status_info
                    },
                    "payment_type": payment_type.value if payment_type else None,
                    "payment_status": order.get('payment_status', 'pending'),
                    "possible_next_statuses": [
                        {
                            "status": status.value,
                            "info": OrderStatusDisplay.get_status_info(status)
                        } for status in possible_next_statuses
                    ],
                    "status_history": status_history,
                    "updated_time": order['updated_time'].isoformat() if order.get('updated_time') else None
                }
            }
            
        except ValueError as e:
            return {"success": False, "message": f"无效的状态值：{str(e)}"}
        except Exception as e:
            return {"success": False, "message": f"获取状态信息失败：{str(e)}"}
    
    def get_orders_by_status(self, status: str, user_id: str = None, 
                           limit: int = 20, offset: int = 0) -> Dict[str, Any]:
        """根据状态获取订单列表"""
        try:
            # 验证状态值
            try:
                OrderStatus(status)
            except ValueError:
                return {"success": False, "message": "无效的状态值"}
            
            # 构建查询条件
            where_conditions = ["order_status = %s"]
            params = [status]
            
            if user_id:
                where_conditions.append("customer_id = %s")
                params.append(user_id)
            
            # 查询订单
            sql = f"""
                SELECT 
                    order_id, order_no, customer_id, salesman_id,
                    order_status, payment_status, payment_method,
                    total_amount, final_amount, shipping_fee,
                    created_time, updated_time
                FROM orders 
                WHERE {' AND '.join(where_conditions)}
                ORDER BY updated_time DESC
                LIMIT %s OFFSET %s
            """
            params.extend([limit, offset])
            
            orders = self.order_repo.execute_custom_query(sql, params, True)
            
            # 格式化订单信息
            formatted_orders = []
            for order in orders or []:
                order_status = OrderStatus(order['order_status'])
                status_info = OrderStatusDisplay.get_status_info(order_status)
                
                formatted_orders.append({
                    "order_id": order['order_id'],
                    "order_no": order['order_no'],
                    "status": {
                        "status": order['order_status'],
                        "info": status_info
                    },
                    "payment_status": order['payment_status'],
                    "payment_method": order['payment_method'],
                    "total_amount": float(order['total_amount']),
                    "final_amount": float(order['final_amount']),
                    "shipping_fee": float(order['shipping_fee']),
                    "created_time": order['created_time'].isoformat() if order.get('created_time') else None,
                    "updated_time": order['updated_time'].isoformat() if order.get('updated_time') else None
                })
            
            # 获取总数
            count_sql = f"""
                SELECT COUNT(*) as total 
                FROM orders 
                WHERE {' AND '.join(where_conditions)}
            """
            count_result = self.order_repo.execute_custom_query(count_sql, params[:-2], True)
            total = count_result[0]['total'] if count_result else 0
            
            return {
                "success": True,
                "data": {
                    "orders": formatted_orders,
                    "total": total,
                    "limit": limit,
                    "offset": offset,
                    "status_filter": status
                }
            }
            
        except Exception as e:
            return {"success": False, "message": f"获取订单列表失败：{str(e)}"}
    
    def get_status_statistics(self, user_id: str = None) -> Dict[str, Any]:
        """获取订单状态统计"""
        try:
            # 构建查询条件
            where_condition = ""
            params = []
            
            if user_id:
                where_condition = "WHERE customer_id = %s"
                params.append(user_id)
            
            # 查询状态统计
            sql = f"""
                SELECT 
                    order_status,
                    COUNT(*) as count,
                    SUM(final_amount) as total_amount
                FROM orders 
                {where_condition}
                GROUP BY order_status
                ORDER BY 
                    CASE order_status
                        WHEN 'pending' THEN 1
                        WHEN 'submitted' THEN 2
                        WHEN 'paid' THEN 3
                        WHEN 'shipped' THEN 4
                        WHEN 'delivered' THEN 5
                        WHEN 'signed' THEN 6
                        WHEN 'receipt_pending' THEN 7
                        WHEN 'receipt_uploaded' THEN 8
                        WHEN 'completed' THEN 9
                        ELSE 10
                    END
            """
            
            results = self.order_repo.execute_custom_query(sql, params, True)
            
            # 格式化统计数据
            statistics = []
            for result in results or []:
                try:
                    status = OrderStatus(result['order_status'])
                    status_info = OrderStatusDisplay.get_status_info(status)
                    
                    statistics.append({
                        "status": result['order_status'],
                        "status_info": status_info,
                        "count": result['count'],
                        "total_amount": float(result['total_amount'] or 0)
                    })
                except ValueError:
                    # 跳过无效状态
                    continue
            
            return {
                "success": True,
                "data": {
                    "statistics": statistics,
                    "total_orders": sum(s['count'] for s in statistics),
                    "total_amount": sum(s['total_amount'] for s in statistics)
                }
            }
            
        except Exception as e:
            return {"success": False, "message": f"获取状态统计失败：{str(e)}"}
    
    def _log_status_change(self, order_id: str, old_status: str, new_status: str,
                          operator_type: str, operator_id: str = None, notes: str = None):
        """记录状态变更日志"""
        try:
            log_record = {
                "log_id": f"LOG{int(datetime.now().timestamp())}{order_id[-6:]}",
                "order_id": order_id,
                "old_status": old_status,
                "new_status": new_status,
                "operator_type": operator_type,  # system, user, admin
                "operator_id": operator_id,
                "notes": notes,
                "created_time": datetime.now()
            }
            
            self.status_log_repo.create(log_record)
        except Exception as e:
            # 日志记录失败不影响主流程
            print(f"记录状态变更日志失败：{str(e)}")
    
    def _get_status_history(self, order_id: str) -> List[Dict[str, Any]]:
        """获取订单状态历史"""
        try:
            sql = """
                SELECT old_status, new_status, operator_type, operator_id, notes, created_time
                FROM order_status_logs 
                WHERE order_id = %s
                ORDER BY created_time DESC
                LIMIT 20
            """
            
            logs = self.status_log_repo.execute_custom_query(sql, [order_id], True)
            
            history = []
            for log in logs or []:
                try:
                    new_status = OrderStatus(log['new_status'])
                    status_info = OrderStatusDisplay.get_status_info(new_status)
                    
                    history.append({
                        "old_status": log['old_status'],
                        "new_status": log['new_status'],
                        "status_info": status_info,
                        "operator_type": log['operator_type'],
                        "operator_id": log['operator_id'],
                        "notes": log['notes'],
                        "created_time": log['created_time'].isoformat() if log.get('created_time') else None
                    })
                except ValueError:
                    # 跳过无效状态
                    continue
            
            return history
            
        except Exception as e:
            print(f"获取状态历史失败：{str(e)}")
            return []
    
    def _get_possible_next_statuses(self, current_status: OrderStatus, payment_type: PaymentType) -> List[OrderStatus]:
        """获取可能的下一个状态"""
        possible_statuses = OrderStatusTransition.VALID_TRANSITIONS.get(current_status, [])
        
        # 根据支付类型过滤状态
        if payment_type == PaymentType.OFFLINE:
            # 线下支付不需要经过已支付状态
            if OrderStatus.PAID in possible_statuses and current_status == OrderStatus.SUBMITTED:
                possible_statuses = [s for s in possible_statuses if s != OrderStatus.PAID]
        
        return possible_statuses
    
    def _get_payment_type_from_method(self, payment_method: str) -> Optional[PaymentType]:
        """根据支付方式确定支付类型"""
        if not payment_method:
            return None
            
        online_methods = ['wechat', 'alipay']
        return PaymentType.ONLINE if payment_method in online_methods else PaymentType.OFFLINE 